package service

import (
	"database/sql"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"math/rand"
	"medical/abac"
	"medical/cpabe"
	"medical/sqlaction"
	"strconv"
	"strings"
	"time"

	"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
)

var BlockInto GetThisBlockInto // 区块信息{firstBlock:[区块编号,区块哈希,时间,操作类型,操作人员ID,针对对象ID]}
var eventIndex int             // 上链事件的编号
// main.go对应的上链初始化 InitUpload()
// funcion: 将baseinfo里的记录上链，对应行为为 generatedata，
// return: 返回 msg map[int]string  和err
func (t *ServiceSetup) InitUpload(user string, orgin string) (GetThisBlockInto, error) {
	DB := InitDB()
	// delete clear operation_record
	_, delerr := DB.Exec(`DELETE FROM operation_record`)
	if delerr != nil {
		fmt.Println(delerr)
	}
	SqlString := "SELECT * FROM(SELECT @n:=@n+1 as n, a.* from (SELECT _SubjectMark,_Researcher,_Organization,_Diseases,_CaseNumber,_GatherTime FROM base_info) a,(SELECT @n:=0)b)c WHERE c.n = '"
	var number int
	var datainfo string
	var casenumberCase string
	//SQLString2 := "select username from login where state='1'"
	err := DB.QueryRow("SELECT COUNT(_CaseNumber) FROM base_info").Scan(&number)
	if err == sql.ErrNoRows { //没有结果
		fmt.Println("err")
	} else {
		for i := 1; i <= number; i++ {
			sqlString := SqlString + strconv.Itoa(i) + "'"
			data := AdvanceQuery(DB, sqlString)
			datainfo = datainfo + data[1] + "," + data[2] + "," + data[3] + "," + data[4] + "," + data[5] + "," + data[6] + ";"
			casenumberCase = data[5]
		}
		datainfo = datainfo[:len(datainfo)-1]
		isSuccess := "T"
		// 初始化上传所有数据
		eventIndex = 0
		respone1, err01 := t.ToChaincode("eventInitUploadMed", eventIndex, "InitUploadMed", datainfo, "Success")
		if err01 != nil {
			fmt.Println(err01)
			GenerateOperationReocrd(DB, eventIndex, user, "AllData", "InitUploadMed", "F", "F")
		} else {
			// 获取区块信息
			block1, _ := t.c.QueryBlockByTxID(respone1.TransactionID)
			BlockInto.ThirdBlock = Getinfo2Block(DB, block1, "GenerateData", user, "AllData", "InitUploadMed", isSuccess, eventIndex)
		}

		// 访问对应的data
		eventIndex = eventIndex + 1
		respone2, err02 := t.ToChaincode("eventGetUploadMed", eventIndex, "GetInitMedInfo", casenumberCase, "Success")
		if err02 != nil {
			fmt.Println(err02)
		}
		var d MedicalRecordForChain
		err2 := json.Unmarshal(respone2.Payload, &d)
		if err2 != nil {
			fmt.Println("反序列化医疗记录失败！")
			GenerateOperationReocrd(DB, eventIndex, user, casenumberCase, "GetInitMedInfo", "F", "F")
		} else {
			fmt.Println(d)
			// 获取区块信息
			block2, _ := t.c.QueryBlockByTxID(respone2.TransactionID)
			BlockInto.SecondBlock = Getinfo2Block(DB, block2, "AccessData", user, d.CaseNumber, "GetInitMedInfo", isSuccess, eventIndex)
		}

		// 链上基于casenumber直接获取所有操作信息 -- AccessMedicalRecord 数据类型为 casenumber+当前用户+用户对应机构
		eventIndex = eventIndex + 1
		AccessMedicalRecordData := casenumberCase + "," + user + "," + orgin
		respone3, _ := t.ToChaincode("AccessMedicalRecord", eventIndex, "AccessMedicalRecord", AccessMedicalRecordData, "Success")
		var medhis MedicalRecordHistoryArr
		err3 := json.Unmarshal(respone3.Payload, &medhis)
		if err3 != nil {
			fmt.Println("反序列化医疗记录失败！")
			GenerateOperationReocrd(DB, eventIndex, user, casenumberCase, "AccessMedicalRecord", "F", "F")
		} else {
			fmt.Println(len(medhis.MRH)) // 2
			fmt.Println(medhis.MRH)
			// 获取区块信息
			block3, _ := t.c.QueryBlockByTxID(respone3.TransactionID)
			BlockInto.FirstBlock = Getinfo2Block(DB, block3, "TraceData", user, casenumberCase, "AccessMedicalRecord", isSuccess, eventIndex)
			BlockHeader3 := block3.GetHeader()
			fmt.Printf("Block: Number=[%d], CurrentBlockHash=[%s], PreviousBlockHash=[%s]\n",
				BlockHeader3.Number,
				base64.StdEncoding.EncodeToString(BlockHeader3.DataHash),
				base64.StdEncoding.EncodeToString(BlockHeader3.PreviousHash))
		}
	}
	return BlockInto, nil
}

// 根据输入的CaseNumber获取相关操作信息，即单独执行一次AccessMedicalRecord合约
func (t *ServiceSetup) AccessMedicalRecord(queryCaseNumber string, user string, orgin string) (MedicalRecordHistoryArr, error) {
	eventIndex = eventIndex + 1
	queryData := queryCaseNumber + "," + user + "," + orgin
	respone0, _ := t.ToChaincode("eventAccessMedicalRecord", eventIndex, "AccessMedicalRecord", queryData, "Success")
	var medhis MedicalRecordHistoryArr
	err0 := json.Unmarshal(respone0.Payload, &medhis)
	if err0 != nil {
		fmt.Println("TEST 反序列化医疗记录失败！")
	} else {
		// 添加对审计的展示
		DB := InitDB()
		isSuccess := "T"
		block, _ := t.c.QueryBlockByTxID(respone0.TransactionID)
		BlockInto = BlockJust3(Getinfo2Block(DB, block, "AuditData", user, queryCaseNumber, "AuditMedicalRecord", isSuccess, eventIndex), BlockInto)
	}
	return medhis, nil
}

// 获取全局变量 Blockinfo
func (t *ServiceSetup) GetBlockInto() GetThisBlockInto {
	return BlockInto
}

// 上链写成函数，传参分别是：事件名称，序列号，链码名称，传入数据, 操作结果
func (t *ServiceSetup) ToChaincode(eventName string, number int, chaincodeName string, data string, resultStr string) (channel.Response, error) {
	eventID := eventName + strconv.Itoa(number)
	reg, notifier := regitserEvent(t.Client, t.ChaincodeID, eventID)
	defer t.Client.UnregisterChaincodeEvent(reg)
	req := channel.Request{ChaincodeID: t.ChaincodeID, Fcn: chaincodeName, Args: [][]byte{[]byte(data), []byte(resultStr), []byte(eventID)}}
	respone, err0 := t.Client.Execute(req)
	fmt.Println("此上链事件生成的交易ID为： " + respone.TransactionID)
	if err0 != nil {
		fmt.Println("执行 " + eventID + " , " + chaincodeName + " 上链出错")
		return respone, err0
	}
	err1 := eventResult(notifier, eventID)
	if err1 != nil {
		fmt.Println("接收 " + eventID + " , " + chaincodeName + " 链码出错,事件ID未知")
		return respone, err1
	}
	return respone, nil
}

// 增 上传med
func (t *ServiceSetup) UploadMed(args []string) (string, error) {
	DB := InitDB()
	var subject string
	row := DB.QueryRow("select count(*) from base_info where _SubjectMark='" + args[0] + "' limit 1")
	row.Scan(&subject)
	fmt.Println("================================", subject)
	if subject != "0" {
		return "", nil
	}

	var groups, owner, usertype, org, userrole, disease, casenumber, policy, mess, str string
	// owner := sqlaction.GetUserLogin(DB, "select username from login where state='1'") //确定用户名
	rows := DB.QueryRow("select username,usertype from login where state='1'")
	rows.Scan(&owner, &usertype)
	rows = DB.QueryRow("select user_insti, user_disease,user_role from user_type where user_id='" + usertype + "'")
	rows.Scan(&org, &disease, &userrole)
	if userrole == "u3" {
		return "", fmt.Errorf("该用户为u3，无上传权限！")
	}
	// TODO: Groups由哪里获得
	groups = "xxx"
	arr := [17]string{}
	// args[0]是subject，1是txt
	arr[0] = groups
	arr[1] = args[0]
	arr[7] = disease
	arr[11] = owner
	arr[12] = org
	policy = ""
	casenumber = sqlaction.GetCaseNumber(arr[:])
	// TODO: 这里数据添加，数据不全，后面问一下
	isSuccess := "F"
	if !InsertDB(DB, arr[:], casenumber) {
		return "", fmt.Errorf("数据库插入不成功！")
	} else {
		if InsertDB2Insti(DB, casenumber) {
			// var arr [6]string
			// rows := DB.QueryRow("select _Groups,_SubjectMark,_Diseases,_Researcher,_Organization,_GatherTime FROM base_info where _CaseNumber='" + casenumber + "'")
			// rows.Scan(&arr[0], &arr[1], &arr[2], &arr[3], &arr[4], &arr[5])
			// result := make(map[int]string)
			// result = queryDB(DB, "select insti_name from insti_coop where _CaseNumber='"+casenumber+"'")
			// for _, v := range result {
			// 	o = o + " " + v
			// }
			policy = InitPolicy(DB, casenumber)

			SQLString := "select * from policy where policy_id='" + casenumber + "'"
			err := DB.QueryRow(SQLString).Scan(&str)
			if err == sql.ErrNoRows { //没有结果
				SQLString3 := "insert into policy(policy_id,policy_data)values(?,?)"
				_, err := DB.Exec(SQLString3, casenumber, policy)
				if err != nil {
					fmt.Println("err")
				}
			}
			isSuccess = "T"
			fmt.Println(policy)
			if policy != "" {
				// 修改上链流程 By J 230320 涉及到的上链都可直接这样调用
				eventIndex = eventIndex + 1
				UplodaInfo := casenumber + ";" + args[11] + ";" + args[12]
				respone, err1 := t.ToChaincode("eventUploadMed", eventIndex, "UploadMedicalRecord", UplodaInfo, "Success")
				if err1 != nil {
					fmt.Println(err1)
					GenerateOperationReocrd(DB, eventIndex, owner, casenumber, "UploadMedicalRecord", isSuccess, "F")
				} else {
					block, _ := t.c.QueryBlockByTxID(respone.TransactionID)
					BlockInto = BlockJust3(Getinfo2Block(DB, block, "GenerateData", owner, casenumber, "UploadMedicalRecord", isSuccess, eventIndex), BlockInto)
				}
				mess = string(respone.TransactionID)[0:6] + " : " + casenumber + "-policy = " + policy
			} else {
				GenerateOperationReocrd(DB, eventIndex, owner, casenumber, "UploadMedicalRecord", "F", "F")
				return "", nil
			}
		}
	}

	//return policy, nil
	//return string(respone.TransactionID), nil
	return mess, nil
}

// 操作记录的数据获取
func (t *ServiceSetup) OperationRecord() ([]TableRow, error) {
	DB := InitDB()
	// var return_str1, return_str2, resultStr string
	var username, usertype string
	// owner := sqlaction.GetUserLogin(DB, "select username from login where state='1'") //确定用户名
	rows := DB.QueryRow("select username,usertype from login where state='1'")
	rows.Scan(&username, &usertype)
	fmt.Println("username is ", username)

	// var gatherTime, medicalRecordID, actionType, isSuccess map[int]string
	// rows = DB.QueryRow("select _GatherTime, MedicalRecordID,ActionType,IsSuccess from operation_record where UserID='" + username + "'")
	// rows.Scan(&gatherTime, &medicalRecordID, &actionType, &isSuccess)

	SQLString1 := "select _GatherTime from operation_record where UserID='" + username + "'"
	gatherTime := queryDB(DB, SQLString1)
	SQLString2 := "select MedicalRecordID from operation_record where UserID='" + username + "'"
	medicalRecordID := queryDB(DB, SQLString2)
	SQLString3 := "select ActionType from operation_record where UserID='" + username + "'"
	actionType := queryDB(DB, SQLString3)
	SQLString4 := "select IsSuccess from operation_record where UserID='" + username + "'"
	isSuccess := queryDB(DB, SQLString4)

	fmt.Println("the medicalRecordID is ", medicalRecordID)

	var tabledata []TableRow
	for i := 0; i < len(medicalRecordID); i++ {

		var tablerow TableRow
		// 第一列序号
		tablerow.FirstColumn = strings.Split(gatherTime[i], " ")[0]
		// 第二列subjectmark
		tablerow.SecondColumn = strings.Split(gatherTime[i], " ")[1]
		// 第三列caseNumber
		tablerow.ThirdColumn = medicalRecordID[i]
		// 第四列返回结果
		tablerow.FourthColumn = actionType[i]
		// 第五列备注
		if isSuccess[i] == "T" {
			tablerow.FifthColumn = "成功"
		} else {
			tablerow.FifthColumn = "失败"
		}
		// 第六列策略已生成
		// tablerow.SixthColumn = "已生成"
		fmt.Println("第", i, "次的tablerow为：", tablerow)
		tabledata = append(tabledata, tablerow)
	}
	return tabledata, nil
	// return return_str1, return_str2, nil
}

// read med
func (t *ServiceSetup) ReadMed( /*userid string,*/ casenumer string) (string, string, string) {
	DB := InitDB()
	isSuccess := "F"
	var return_str1, return_str2, resultStr string
	isAccese, resultAccess := CheckAction(DB, casenumer, "r")
	if !isAccese {
		return_str1 = "NULL"
		return_str2 = "访问失败"
		resultStr = "Fail"
		fmt.Errorf("权限不足，无法操作")
	} else {
		SQLString := "select _SubjectMark from base_info where _CaseNumber ='" + casenumer + "'"
		err := DB.QueryRow(SQLString).Scan(&return_str1)
		if err != nil {
			return "NULL", "访问失败", resultAccess
		}
		return_str2 = "访问成功"
		resultStr = "Success"
		resultAccess = "已返回病历编号"
		isSuccess = "T"
	}

	// TODO：上链
	var owner, usertype, org, disease string
	// owner := sqlaction.GetUserLogin(DB, "select username from login where state='1'") //确定用户名
	rows := DB.QueryRow("select username,usertype from login where state='1'")
	rows.Scan(&owner, &usertype)
	rows = DB.QueryRow("select user_insti, user_disease from user_type where user_id='" + usertype + "'")
	rows.Scan(&org, &disease)
	//var uid string
	//SQLString := "select username from login where state='1'" // username
	//err := DB.QueryRow(SQLString).Scan(&uid)
	//if err != nil { //没有结果
	//	fmt.Println("err, can't find logined user")
	//	return "", "", err
	//}
	op := "AccessData" // access
	eventIndex = eventIndex + 1
	argsInfo := casenumer + ";" + owner + ";" + op + ";" + org + ";" + disease
	respone, err1 := t.ToChaincode("eventReadMed", eventIndex, "ReadMedicalRecord", argsInfo, resultStr)
	if err1 != nil {
		fmt.Println(err1)
		GenerateOperationReocrd(DB, eventIndex, owner, casenumer, "ReadMedicalRecord", isSuccess, "F")
	} else {
		block, _ := t.c.QueryBlockByTxID(respone.TransactionID)
		BlockInto = BlockJust3(Getinfo2Block(DB, block, "AccessData", owner, casenumer, "ReadMedicalRecord", isSuccess, eventIndex), BlockInto)
	}
	// eventID := "eventAccessMed"
	// reg, notifier := regitserEvent(t.Client, t.ChaincodeID, eventID)
	// defer t.Client.UnregisterChaincodeEvent(reg)
	// resultStr := "success"
	// req := channel.Request{ChaincodeID: t.ChaincodeID, Fcn: "AccessMedicalRecord", Args: [][]byte{[]byte(casenumer), []byte(resultStr), []byte(eventID)}}
	// respone, err0 := t.Client.Execute(req)
	// if err0 != nil {
	// 	return respone.Payload, err0
	// }
	// var str string
	// err := json.Unmarshal(respone.Payload, &str)
	// if err != nil {
	// 	return []byte{0x00}, err
	// }
	// err1 := eventResult(notifier, eventID)
	// if err1 != nil {
	// 	return []byte{0x00}, err1
	// }
	// mp := SelectDBSingle(DB, casenumer)
	// if mp == nil {
	// 	return []byte{0x00}, fmt.Errorf("数据库查询不成功！")
	// }
	/*
		m := *mp
		b, err2 := json.Marshal(m)
		if err2 != nil {
			return []byte{0x00}, err2
		}
	*/
	return return_str1, return_str2, resultAccess
}

// 改 修改policy
func (t *ServiceSetup) UpdataPolicy(subjectmark string, casenumber string, args []string) (string, error) {
	DB := InitDB()
	// var groups, owner, usertype, org, disease, casenumer, policy, mess string

	// TODO:重新生成  把原有的删掉
	// TODO: 但是删除的函数是 DeleteDB
	var oldPolicy_str, mess string
	row := DB.QueryRow("select policy_data from policy where policy_id='" + casenumber + "'")
	row.Scan(&oldPolicy_str)
	fmt.Println("the old policy is", oldPolicy_str)
	if oldPolicy_str == "" {
		fmt.Println("不存在该访问策略")
		mess = subjectmark + "不存在访问策略"
		return mess, nil
	}
	var oldPolicy abac.Policy
	err := json.Unmarshal([]byte(oldPolicy_str), &oldPolicy)
	if err != nil {
		fmt.Print("参数化失败")
	}

	policy_str := UpdataPolicy(DB, oldPolicy, args)
	fmt.Println("new policy is: ", policy_str)

	// 删除原Policy
	fmt.Println("====delete the old policy===")
	SQLString3 := "delete from policy where policy_id = ?"
	stmt, _ := DB.Prepare(SQLString3)
	_, err0 := stmt.Exec(casenumber)
	if err0 != nil {
		fmt.Println("删除失败:", err0.Error())
		return "删除失败", err0
	}

	// 插入数据库
	SQLString2 := "insert into policy(policy_id,policy_data)values(?,?)"
	_, err = DB.Exec(SQLString2, casenumber, policy_str)
	if err != nil {
		fmt.Println("插入失败：", err.Error())
		return "插入失败", err
	}

	mess = policy_str
	return mess, nil
}

// 获取共享数据
func (t *ServiceSetup) GetShareData() ([]TableRow, error) {
	var tabledata []TableRow
	var owner, org string
	//TODO:确定用户名，这里需要每个函数都调用么？有全局变量吗？
	Sqlstring := "select username,usertype from login where state='1'"
	rows := AdvanceQuery(DB, Sqlstring)
	rows2 := DB.QueryRow("select user_insti from user_type where user_id='" + rows[1] + "'")
	rows2.Scan(&org)
	owner = rows[0]

	SQLString1 := "select _SubjectMark from base_info where _Researcher='" + owner + "' AND _Organization='" + org + "' AND _Addition1!=''"
	_SubjectMark := queryDB(DB, SQLString1)
	SQLString2 := "select _CaseNumber from base_info where _Researcher='" + owner + "' AND _Organization='" + org + "' AND _Addition1!=''"
	_CaseNumber := queryDB(DB, SQLString2)
	SQLString3 := "select _BaseTime from base_info where _Researcher='" + owner + "' AND _Organization='" + org + "' AND _Addition1!=''"
	_BaseTime := queryDB(DB, SQLString3)
	SQLString4 := "select _Addition1 from base_info where _Researcher='" + owner + "' AND _Organization='" + org + "' AND _Addition1!=''"
	_Addition1 := queryDB(DB, SQLString4)
	SQLString5 := "select _Addition2 from base_info where _Researcher='" + owner + "' AND _Organization='" + org + "' AND _Addition1!=''"
	_Addition2 := queryDB(DB, SQLString5)
	for i := 0; i < len(_SubjectMark); i++ {

		var tablerow TableRow
		// 第一列序号
		tablerow.FirstColumn = _SubjectMark[i]
		// 第二列subjectmark
		tablerow.SecondColumn = _CaseNumber[i]
		// 第三列caseNumber
		tablerow.ThirdColumn = _BaseTime[i]
		// 第四列返回结果
		tablerow.FourthColumn = _Addition1[i]
		// 第五列备注
		tablerow.FifthColumn = _Addition2[i]
		// 第六列策略已生成
		tablerow.SixthColumn = "已生成"
		tabledata = append(tabledata, tablerow)
	}
	return tabledata, nil
}

// 得到搜索结果并转为列表数据
func (t *ServiceSetup) GetResearchData(data [][]interface{}) ([]TableRow, error) {
	var tabledata []TableRow
	for j := 0; j < len(data); j++ {
		var tablerow TableRow
		// 第一列序号
		tablerow.FirstColumn = strconv.Itoa(j + 1)
		// 第二列 caseNumber
		tablerow.SecondColumn = Strval(data[j][4])
		// 第三列 _Diseases
		tablerow.ThirdColumn = Strval(data[j][3])
		// 第四列 __Groups
		tablerow.FourthColumn = Strval(data[j][6])
		// 第五列 _Diagnose
		tablerow.FifthColumn = Strval(data[j][13])
		// 第六列 _Organization
		tablerow.SixthColumn = Strval(data[j][2])
		// 第七列 是否共享
		if data[j][14] != "" {
			tablerow.SeventhColumn = Strval("已共享")
		} else {
			tablerow.SeventhColumn = Strval("")
		}

		tabledata = append(tabledata, tablerow)
	}
	fmt.Println(tabledata)
	return tabledata, nil
}

// 获取未共享数据
func (t *ServiceSetup) GetOtherUnShareData() ([]TableRow, error) {
	DB := InitDB()
	var owner, org string
	//TODO:确定用户名，这里需要每个函数都调用么？有全局变量吗？
	Sqlstring := "select username,usertype from login where state='1'"
	rows := AdvanceQuery(DB, Sqlstring)
	rows2 := DB.QueryRow("select user_insti from user_type where user_id='" + rows[1] + "'")
	rows2.Scan(&org)
	owner = rows[0]
	SQLString1 := "select _SubjectMark from base_info where _Researcher='" + owner + "' AND _Organization='" + org + "' AND (_Addition1='')"
	subjectMark_list := AdvanceQuery(DB, SQLString1)
	// fmt.Println("subjectMark is:", subjectMark_list)
	SQLString2 := "select _CaseNumber from base_info where _Researcher='" + owner + "' AND _Organization='" + org + "' AND (_Addition1='')"
	caseNumber_list := queryDB(DB, SQLString2)
	var tabledata []TableRow
	for i := 0; i < len(subjectMark_list); i++ {

		var tablerow TableRow
		// 第一列序号
		tablerow.FirstColumn = strconv.Itoa(i + 1)
		// 第二列subjectmark
		tablerow.SecondColumn = subjectMark_list[i]
		// 第三列caseNumber
		tablerow.ThirdColumn = caseNumber_list[i]
		// 第四列返回结果
		tablerow.FourthColumn = "成功"
		// 第五列备注
		tablerow.FifthColumn = "无"
		// 第六列策略已生成
		tablerow.SixthColumn = "已生成"
		tabledata = append(tabledata, tablerow)
	}
	fmt.Println("table is:", tabledata)
	return tabledata, nil

}

// 创建共享数据
func (t *ServiceSetup) GenerateShareData(casenumb string, timechoose string) (bool, error) {
	DB := InitDB()
	var data = make([]string, 999)
	if find := strings.Contains(casenumb, ","); find {
		data = strings.Split(casenumb, ",")
	} else {
		data[0] = casenumb
	}
	for i := 0; i < len(data); i++ {
		if data[i] == "" {
			continue
		}
		flag, Enpath, sharecode := cpabe.DataEnShare(DB, data[i], "u1", timechoose)
		if flag {
			sqlstring := "UPDATE base_info SET _Addition1= '" + Enpath + "', _Addition2='" + sharecode + "' where _CaseNumber='" + casenumb + "'"
			_, err := DB.Exec(sqlstring)
			if err != nil {
				fmt.Println("err")
			}
		} else {
			return false, nil
		}
	}
	return true, nil
}

// 修改共享时间
func (t *ServiceSetup) ChangeShareData(casenumb string, timechoose string) (bool, error) {
	DB := InitDB()
	flag := cpabe.DataSharewithTime(DB, casenumb, timechoose)
	return flag, nil
}

// 删除共享数据
func (t *ServiceSetup) DeleteShareData(casenumb string) (bool, error) {
	DB := InitDB()
	flag := cpabe.Delete(DB, casenumb)
	return flag, nil
}

// 匹配共享密码返回数据
func (t *ServiceSetup) MatchGetShareData(casenumb string, secnumb string, owner string, org string) (bool, string, []TableRow) {
	DB := InitDB()
	eventIndex = eventIndex + 1
	var isSuccess = "T"
	flag, sub, datapath := cpabe.ConfirmShare(DB, casenumb, secnumb) // 待改正
	var Msg string
	if flag {
		Msg = "匹配成功"
		// 上链
		op := "AccessData" // access
		argsInfo := casenumb + ";" + owner + ";" + op + ";" + org
		respone, err1 := t.ToChaincode("eventReadMed", eventIndex, "ReadMedicalRecord", argsInfo, "Success")
		if err1 != nil {
			fmt.Println(err1)
			GenerateOperationReocrd(DB, eventIndex, owner, casenumb, "ReadMedicalRecord", isSuccess, "F")
		} else {
			block, _ := t.c.QueryBlockByTxID(respone.TransactionID)
			BlockInto = BlockJust3(Getinfo2Block(DB, block, "AccessData", owner, casenumb, "ReadMedicalRecord", isSuccess, eventIndex), BlockInto)
		}
	} else {
		isSuccess = "F"
		GenerateOperationReocrd(DB, eventIndex, owner, casenumb, "ReadMedicalRecord", isSuccess, "F")
		Msg = datapath
	} //suceess -additon1
	var tabledata []TableRow
	tablerow := TableRow{
		FirstColumn:  "0",
		SecondColumn: sub,
		ThirdColumn:  casenumb,
		FourthColumn: Msg,
		FifthColumn:  datapath,
	}
	tabledata = append(tabledata, tablerow)
	return flag, Msg, tabledata
}

// 针对溯源的页面数据
func (t *ServiceSetup) GetAllDataForTrace() ([]TableRow, error) {
	DB := InitDB()
	SQLString2 := "select _CaseNumber from base_info"
	caseNumber_list := queryDB(DB, SQLString2)
	// 目前只有 caseNumber
	var tabledata []TableRow
	for i := 0; i < len(caseNumber_list); i++ {

		var tablerow TableRow
		// 第一列序号
		tablerow.FirstColumn = strconv.Itoa(i + 1)
		// 第二列 caseNumber
		tablerow.SecondColumn = caseNumber_list[i]
		//// 第三列 未知
		//tablerow.ThirdColumn = caseNumber_list[i]
		//// 第四列 未知
		//tablerow.FourthColumn = "成功"
		//// 第五列 未知
		//tablerow.FifthColumn = "无"
		//// 第六列 未知
		//tablerow.SixthColumn = "已生成"
		tabledata = append(tabledata, tablerow)
	}
	//fmt.Println(tabledata)
	return tabledata, nil

}

// 更新了sql搜索语句，解决因用户不同访问控制策略无法更新的问题 By J 230310
func (t *ServiceSetup) QueryAllMed() ([]TableRow, error) {
	DB := InitDB()
	var owner, org string
	//TODO:确定用户名，这里需要每个函数都调用么？有全局变量吗？
	Sqlstring := "select username,usertype from login where state='1'"
	rows := AdvanceQuery(DB, Sqlstring)
	rows2 := DB.QueryRow("select user_insti from user_type where user_id='" + rows[1] + "'")
	rows2.Scan(&org)
	owner = rows[0]
	fmt.Println("owner is ", owner)
	SQLString1 := "select _SubjectMark from base_info where _Researcher='" + owner + "' AND _Organization='" + org + "'"
	subjectMark_list := queryDB(DB, SQLString1)
	// fmt.Println("subjectMark is:", subjectMark_list)
	SQLString2 := "select _CaseNumber from base_info where _Researcher='" + owner + "' AND _Organization='" + org + "'"
	caseNumber_list := queryDB(DB, SQLString2)

	// fmt.Println("caseNumber is:", caseNumber_list)
	// SQLString3 := "select _CaseNumber from base_info where _Researcher='" + owner + "'"
	// intro := queryDB(DB, SQLString2)
	// fmt.Println("caseNumber is:", caseNumber_list)
	// TODO：这里需要上链吗？
	// mess_map := make(map[int]interface{})
	// var firstColumn []string
	// var secondColumn []string
	var tabledata []TableRow
	for i := 0; i < len(subjectMark_list); i++ {

		var tablerow TableRow
		// 第一列序号
		tablerow.FirstColumn = strconv.Itoa(i + 1)
		// 第二列subjectmark
		tablerow.SecondColumn = subjectMark_list[i]
		// 第三列caseNumber
		tablerow.ThirdColumn = caseNumber_list[i]
		// 第四列返回结果
		tablerow.FourthColumn = "成功"
		// 第五列备注
		tablerow.FifthColumn = "无"
		// 第六列策略已生成
		tablerow.SixthColumn = "已生成"
		tabledata = append(tabledata, tablerow)
	}
	return tabledata, nil

}
func (t *ServiceSetup) QueryPolicy(id string) (string, error) {
	DB := InitDB()

	// 查询subject的policy
	var policy string
	row := DB.QueryRow("select policy_data from policy where policy_id='" + id + "'")
	row.Scan(&policy)

	return policy, nil

}

// func (t *ServiceSetup) AllData(user string) (string, error) {

// }
// read med
func (t *ServiceSetup) OperateMed(casenumer string, userid string, orgin string) (MedicalRecordHistoryArr, error) {
	DB := InitDB()
	///// 这里要对接下
	//if !CheckAction(DB, casenumer, "r") {
	//	return nil, fmt.Errorf("权限不足，无法操作")
	//}
	// 链上基于casenumber直接获取所有操作信息 -- AccessMedicalRecord
	eventIndex = eventIndex + 1
	respone, _ := t.ToChaincode("AccessMedicalRecord", eventIndex, "AccessMedicalRecord", casenumer+","+userid+","+orgin, "Success")
	var medhis MedicalRecordHistoryArr
	err3 := json.Unmarshal(respone.Payload, &medhis)
	if err3 != nil {
		fmt.Println("反序列化医疗记录失败！")
	} else {
		fmt.Println(len(medhis.MRH)) // 2
		fmt.Println(medhis.MRH)
		// 写入溯源操作记录
		isSuccess := "T"
		block, _ := t.c.QueryBlockByTxID(respone.TransactionID)
		BlockInto = BlockJust3(Getinfo2Block(DB, block, "TraceData", userid, casenumer, "AccessMedicalRecord", isSuccess, eventIndex), BlockInto)
	}

	fmt.Println("判断mp前")
	if !SelectDBSingle(DB, casenumer) {
		return MedicalRecordHistoryArr{}, fmt.Errorf("数据库查询不成功！")
	}
	fmt.Println("判断mp后")
	/*
		m := *mp
		b, err2 := json.Marshal(m)
		if err2 != nil {
			return []byte{0x00}, err2
		}
	*/
	return medhis, nil
}

// 删 删除med
func (t *ServiceSetup) DeleteMed(args []string) (string, error) {
	isSuccess := "F"
	if len(args) != 2 {
		return "", fmt.Errorf("给定的参数个数不符合要求！")
	}
	userid := args[0]
	casenumber := args[1]
	DB := InitDB()
	/*
		// casenumer := args[0]
		if !CheckAction(DB, casenumer, "d") {
			return "", fmt.Errorf("权限不足，无法操作")
		}
	*/

	if !DeleteDB(DB, casenumber) {
		return "", fmt.Errorf("删除数据不成功！")
	}
	// 修改上链流程 By J 230320 涉及到的上链都可直接这样调用 -- 此功能不可用--当上传一个新的数据时，此casenumber无法在链上找到
	// 已解决，删除了判断语句 Data中的字段记录标识 NumFlag  bool //是否记录病例号 -- 调用未做任何操作
	eventIndex = eventIndex + 1
	DataInfo := casenumber + ";" + userid
	respone, err1 := t.ToChaincode("eventDeleteMed", eventIndex, "DeleteMedicalRecord", DataInfo, "Success")
	if err1 != nil {
		fmt.Println(err1)
	} else {
		// 获取区块信息
		isSuccess = "T"
		block, _ := t.c.QueryBlockByTxID(respone.TransactionID)
		BlockInto = BlockJust3(Getinfo2Block(DB, block, "DeleteData", userid, casenumber, "DeleteMedicalRecord", isSuccess, eventIndex), BlockInto)
	}
	return string(respone.TransactionID), nil
	//return "Success", nil
}

func (t *ServiceSetup) UpdateMed(args []string) (string, error) {
	// arr := [5]string{data.Msg, data.CurrentUser.LoginName, r.FormValue("disease"), r.FormValue("group"), r.FormValue("diagnose")}
	fmt.Println(args)
	var isSuccess string
	if len(args) != 5 {
		return "", fmt.Errorf("给定的参数个数不符合要求！")
	}
	DB := InitDB()
	/*
		casenumer := args[0]
		if !CheckAction(DB, casenumer, "w") {
			return "", fmt.Errorf("权限不足，无法操作")
		}
	*/
	if !UpdateDB(DB, args) {
		return "", fmt.Errorf("数据库修改不成功！")
	}
	eventIndex = eventIndex + 1
	DataInfo := args[0] + ";" + args[1]
	respone, err1 := t.ToChaincode("eventUpdateMed", eventIndex, "UpdateMedicalRecord", DataInfo, "Success")
	if err1 != nil {
		fmt.Println(err1)
	} else {
		// 获取区块信息
		isSuccess = "T"
		block, _ := t.c.QueryBlockByTxID(respone.TransactionID)
		BlockInto = BlockJust3(Getinfo2Block(DB, block, "UpdateData", args[1], args[0], "UpdateMedicalRecord", isSuccess, eventIndex), BlockInto)
	}
	return string(respone.TransactionID), nil
}

// 用户注册
func (t *ServiceSetup) UserRegister(phone string, identity string) (bool, string) {
	DB := InitDB()
	SQLString1 := "select username from login where identity='" + identity + "'"
	var id string
	err1 := DB.QueryRow(SQLString1).Scan(&id)
	if err1 == sql.ErrNoRows {
		return true, "当前用户可以注册"
	} else {
		return false, "当前身份证已被注册，请直接登录"
	}

}

// 用户身份验证
func (t *ServiceSetup) UserVerify(authen string, insti string, realname string, password string, identity string, phone string, role string) (bool, error) {
	DB := InitDB()
	rand.Seed(time.Now().Unix())
	var insti_num string
	SQLString := "select insti_code from insti_info where insti_name='" + insti + "'"
	err := DB.QueryRow(SQLString).Scan(&insti_num)
	if err == sql.ErrNoRows { //没有结果
		fmt.Println("err")
		return false, err
	} else {
		if insti_num == authen {
			for {
				port := rand.Int63n(10000-1000) + 1000
				usertype := strconv.FormatInt(port, 10)
				var exusertype string
				SQLString1 := "select username from login where usertype='" + usertype + "'"
				err1 := DB.QueryRow(SQLString1).Scan(&exusertype)
				if err1 == sql.ErrNoRows {
					SQLString3 := "insert into user_type(user_id,user_role,user_insti,user_disease)values(?,?,?,?)"
					_, err3 := DB.Exec(SQLString3, usertype, role, insti, "")
					if err3 != nil {
						return false, err3
					}
					SQLString2 := "insert into login(username,password,identity,phone_number,usertype)values(?,?,?,?,?)"
					_, err2 := DB.Exec(SQLString2, realname, password, identity, phone, usertype)
					if err2 != nil {
						fmt.Println(err2)
						return false, err2
					}
					return true, err
				}
			}
		}
	}
	return false, err
}

// 身份证重置密码
func (t *ServiceSetup) UserPwResetId(id string, realname string) (bool, error) {
	DB := InitDB()
	var name string
	SQLString := "select username from login where identity='" + id + "'"
	err := DB.QueryRow(SQLString).Scan(&name)

	if err == sql.ErrNoRows { //没有结果
		return false, err
	} else {
		if name != realname {
			return false, nil
		} else {
			return true, nil
		}
	}
	// flag, num := CertificationId(DB, id)
	// if flag == false && num == 0 {
	// 	fmt.Println("身份证号不和规范，请重新输入")
	// 	return flag, nil
	// } else if flag == false && num == 2 {
	// 	fmt.Println("身份证号在系统中不存在，请返回并注册")
	// 	return flag, nil
	// }
	// return true, nil
}

// 手机号重置密码
func (t *ServiceSetup) UserPwResetPhone(phone string) (bool, error) {
	DB := InitDB()
	flag, num := CertificationPhone(DB, phone)
	if flag == false && num == 0 {
		fmt.Println("手机号不和规范，请重新输入")
		return flag, nil
	} else if flag == false && num == 2 {
		fmt.Println("手机号在系统中不存在，请返回并注册")
		return flag, nil
	}
	return true, nil
}

// 重新输入密码重置
func (t *ServiceSetup) UserPwReset(password string, id string, phone string) (bool, error) {
	DB := InitDB()
	if id != "" {
		SQLString := "UPDATE login SET password= '" + password + "' where identity='" + id + "'"
		_, err := DB.Exec(SQLString)
		if err != nil {
			return false, err
		}
	} else {
		SQLString := "UPDATE login SET password= '" + password + "' where phone_number='" + phone + "'"
		_, err := DB.Exec(SQLString)
		if err != nil {
			return false, err
		}
	}
	return true, nil
}

// 添加机构信息
func (t *ServiceSetup) Addinstitution(instiname string) (bool, error) {
	DB := InitDB()
	var insti_name string
	SQLString2 := "select insti_id from insti_info where insti_name='" + instiname + "'"
	err := DB.QueryRow(SQLString2).Scan(&insti_name)

	if err == sql.ErrNoRows { //没有结果
		insti_id := fmt.Sprintf("%03v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000))
		var insti_num string
		SQLString := "select insti_code from insti_info where insti_id='" + insti_id + "'"
		err := DB.QueryRow(SQLString).Scan(&insti_num)
		if err == sql.ErrNoRows { //没有结果
			SQLString1 := "insert into insti_info(insti_id,insti_name,insti_code)values(?,?,?)"
			_, err1 := DB.Exec(SQLString1, insti_id, instiname, "000000")
			if err1 != nil {
				return false, err1
			}
		} else {
			return false, err
		}
		return true, nil
	} else {
		fmt.Println("该机构已经存在")
		return false, err
	}
}

// 用户登陆后修改密码
func (t *ServiceSetup) Changepassword(name string, oldpassword string, newpassword string) (bool, error) {
	DB := InitDB()
	var password string
	SQLString := "select password from login where username='" + name + "'"
	err := DB.QueryRow(SQLString).Scan(&password)
	if err == sql.ErrNoRows { //没有结果
		return false, err
	} else {
		if password != oldpassword {
			fmt.Println("输入原有密码错误，请重新输入")
			return false, err
		}
		SQLString2 := "UPDATE login SET password='" + newpassword + "' where username='" + name + "'"
		_, err := DB.Exec(SQLString2)
		if err != nil {
			return false, err
		}
		return true, nil
	}
}

// 用户登陆后修改手机号
func (t *ServiceSetup) Changephone(name string, newphone string) (bool, error) {
	DB := InitDB()
	var id1 string
	SQLString := "select identity from login where phone_number='" + newphone + "'"
	err := DB.QueryRow(SQLString).Scan(&id1)
	if err == sql.ErrNoRows { //没有结果
		var oldphone string
		SQLString2 := "select phone_number from login where username='" + name + "'"
		err1 := DB.QueryRow(SQLString2).Scan(&oldphone)
		if err1 == sql.ErrNoRows { //没有结果
			return false, err1
		} else {
			if newphone == oldphone {
				fmt.Println("输入的新手机号与原手机号重复，请重新输入")
				return false, err
			}
			SQLString2 := "UPDATE login SET phone_number='" + newphone + "' where username='" + name + "'"
			_, err := DB.Exec(SQLString2)
			if err != nil {
				return false, err
			}
			return true, nil
		}
	} else {
		return false, err
	}
}

// 用户登陆后修改研究疾病类型
func (t *ServiceSetup) Changedisease(name string, newdisease string) (bool, error) {
	DB := InitDB()
	var usertype string
	SQLString := "select usertype from login where username='" + name + "'"
	err := DB.QueryRow(SQLString).Scan(&usertype)
	if err == sql.ErrNoRows { //没有结果
		return false, err
	} else {
		var userdisease string
		SQLString2 := "select user_disease from user_type where user_id='" + usertype + "'"
		err1 := DB.QueryRow(SQLString2).Scan(&userdisease)
		if err1 == sql.ErrNoRows { //没有结果
			return false, err1
		} else {
			if userdisease == "" {
				SQLString3 := "UPDATE user_type SET user_disease='" + newdisease + "' where user_id='" + usertype + "'"
				_, err2 := DB.Exec(SQLString3)
				if err2 != nil {
					return false, err2
				}
				return true, nil
			} else {
				SQLString3 := "UPDATE user_type SET user_disease='" + newdisease + "、" + userdisease + "' where user_id='" + usertype + "'"
				_, err2 := DB.Exec(SQLString3)
				if err2 != nil {
					return false, err2
				}
				return true, nil
			}
		}
	}
}

// 用于登录前获取当前已有机构
func (t *ServiceSetup) GetAllInsti() (string, error) {
	DB := InitDB()
	SQLString2 := "select insti_name from insti_info"
	insti_name_list := queryDB(DB, SQLString2)
	// 目前只有 insti_name
	var AllInsti string
	for i := 0; i < len(insti_name_list); i++ {
		AllInsti = AllInsti + insti_name_list[i] + ";"
	}
	return AllInsti[:len(AllInsti)-1], nil

}

// 用户注册+设置状态
func (t *ServiceSetup) UserLogin(username string, password string) (bool, error) {
	DB := InitDB()
	SQLString := "select username from login"
	Username := make(map[int]string)
	Username = queryDB(DB, SQLString)

	for _, user := range Username {
		if user == username {
			var str string
			SQLString2 := "select password from login where username='" + user + "'"
			err := DB.QueryRow(SQLString2).Scan(&str)
			if err != sql.ErrNoRows && str == password {
				SQLString3 := "UPDATE login SET state= '1' where username='" + user + "'"
				_, err := DB.Exec(SQLString3)
				if err != nil {
					return false, err
				}
				return true, nil
			}
		}
	}
	return false, nil
}

// 获取登录后用户信息
// return : username(login), user_role(user_type), user_insti(user_type)
func (t *ServiceSetup) UserLoginInfo() (map[int]string, error) {
	DB := InitDB()
	result := make(map[int]string)
	var str, queryInsti string
	SQLString := "select username from login where state ='1'"
	err := DB.QueryRow(SQLString).Scan(&str)
	if err != sql.ErrNoRows {
		result[0] = str
	}
	SQLString1 := "select usertype from login where state ='1'"
	err1 := DB.QueryRow(SQLString1).Scan(&str)
	if err1 != sql.ErrNoRows {
		// 这里无法获取数据，原因未知,
		SQLString2 := "select user_role, user_insti from user_type where user_id ='" + str + "'"
		err := DB.QueryRow(SQLString2).Scan(&str, &queryInsti)
		if err != sql.ErrNoRows {
			result[1] = str
			result[2] = queryInsti
			return result, nil
		}
	}
	return result, nil
}

// 获取登录用户信息--无用 基于用户编号解析角色
/*
func (t *ServiceSetup) GetLoginUserInfo(username string) map[int]string {
	DB := InitDB()
	SQLString := "select * from login where username='" + username + "'"
	result := make(map[int]string)
	result = queryDB(DB, SQLString)
	int, _ := strconv.Atoi(result[4])
	if int <= 9 {
		result[4] = "admin"
	} else if int <= 99 {
		result[4] = "u1"
	} else if int <= 999 {
		result[4] = "u2"
	} else if int <= 9999 {
		result[4] = "u3"
	}
	return result
}
*/

func (t *ServiceSetup) UserLoginOut() (bool, error) {
	DB := InitDB()
	Userinfo := sqlaction.GetUserLogin(DB, "select username from login where state='1'") //确定用户名
	SQLString3 := "UPDATE login SET state= '0' where username='" + Userinfo + "'"
	_, err := DB.Exec(SQLString3)
	if err != nil {
		return false, err
	}
	return true, nil
}

func (t *ServiceSetup) AuditAll(args []string) ([]byte, error) {
	if len(args) != 3 {
		return []byte{0x00}, fmt.Errorf("给定的参数个数不符合要求！")
	}
	eventID := "eventAuditAll"
	reg, notifier := regitserEvent(t.Client, t.ChaincodeID, eventID)
	defer t.Client.UnregisterChaincodeEvent(reg)
	req := channel.Request{ChaincodeID: t.ChaincodeID, Fcn: "auditForAllLogs", Args: [][]byte{[]byte(args[0]), []byte(args[1]), []byte(args[2]), []byte(eventID)}}
	respone, err0 := t.Client.Execute(req)
	if err0 != nil {
		return []byte{0x00}, err0
	}
	err1 := eventResult(notifier, eventID)
	if err1 != nil {
		return []byte{0x00}, err1
	}
	return respone.Payload, nil
}
func (t *ServiceSetup) AuditTimeRange(args []string) ([]byte, error) {
	if len(args) != 5 {
		return []byte{0x00}, fmt.Errorf("给定的参数个数不符合要求！")
	}
	eventID := "eventAuditTimeRange"
	reg, notifier := regitserEvent(t.Client, t.ChaincodeID, eventID)
	defer t.Client.UnregisterChaincodeEvent(reg)
	req := channel.Request{ChaincodeID: t.ChaincodeID, Fcn: "auditForTimeRange", Args: [][]byte{[]byte(args[0]), []byte(args[1]), []byte(args[2]), []byte(args[3]), []byte(args[4]), []byte(eventID)}}
	respone, err0 := t.Client.Execute(req)
	if err0 != nil {
		return []byte{0x00}, err0
	}

	err1 := eventResult(notifier, eventID)
	if err1 != nil {
		return []byte{0x00}, err1
	}

	return respone.Payload, nil
}
func (t *ServiceSetup) AuditUser(args []string) ([]byte, error) {
	if len(args) != 4 {
		return []byte{0x00}, fmt.Errorf("给定的参数个数不符合要求！")
	}
	eventID := "eventAuditUser"
	reg, notifier := regitserEvent(t.Client, t.ChaincodeID, eventID)
	defer t.Client.UnregisterChaincodeEvent(reg)
	req := channel.Request{ChaincodeID: t.ChaincodeID, Fcn: "auditForUser", Args: [][]byte{[]byte(args[0]), []byte(args[1]), []byte(args[2]), []byte(args[3]), []byte(eventID)}}
	respone, err0 := t.Client.Execute(req)
	if err0 != nil {
		return []byte{0x00}, err0
	}

	err1 := eventResult(notifier, eventID)
	if err1 != nil {
		return []byte{0x00}, err1
	}

	return respone.Payload, nil
}
func (t *ServiceSetup) AuditOrganisation(args []string) ([]byte, error) {
	if len(args) != 4 {
		return []byte{0x00}, fmt.Errorf("给定的参数个数不符合要求！")
	}
	eventID := "eventAuditOrganisation"
	reg, notifier := regitserEvent(t.Client, t.ChaincodeID, eventID)
	defer t.Client.UnregisterChaincodeEvent(reg)
	req := channel.Request{ChaincodeID: t.ChaincodeID, Fcn: "auditForOrganisation", Args: [][]byte{[]byte(args[0]), []byte(args[1]), []byte(args[2]), []byte(args[3]), []byte(eventID)}}
	respone, err0 := t.Client.Execute(req)
	if err0 != nil {
		return []byte{0x00}, err0
	}

	err1 := eventResult(notifier, eventID)
	if err1 != nil {
		return []byte{0x00}, err1
	}

	return respone.Payload, nil
}
func (t *ServiceSetup) AuditMedicalRecord(args []string) ([]byte, error) {
	if len(args) != 4 {
		return []byte{0x00}, fmt.Errorf("给定的参数个数不符合要求！")
	}
	eventID := "eventAuditMedicalRecord"
	reg, notifier := regitserEvent(t.Client, t.ChaincodeID, eventID)
	defer t.Client.UnregisterChaincodeEvent(reg)
	req := channel.Request{ChaincodeID: t.ChaincodeID, Fcn: "auditForMedicalRecord", Args: [][]byte{[]byte(args[0]), []byte(args[1]), []byte(args[2]), []byte(args[3]), []byte(eventID)}}
	respone, err0 := t.Client.Execute(req)
	if err0 != nil {
		return []byte{0x00}, err0
	}

	err1 := eventResult(notifier, eventID)
	if err1 != nil {
		return []byte{0x00}, err1
	}

	return respone.Payload, nil
}
func (t *ServiceSetup) AuditOriginalAuthor(args []string) ([]byte, error) {
	if len(args) != 4 {
		return []byte{0x00}, fmt.Errorf("给定的参数个数不符合要求！")
	}
	eventID := "eventAuditOriginalAuthor"
	reg, notifier := regitserEvent(t.Client, t.ChaincodeID, eventID)
	defer t.Client.UnregisterChaincodeEvent(reg)
	req := channel.Request{ChaincodeID: t.ChaincodeID, Fcn: "auditForOriginalAuthor", Args: [][]byte{[]byte(args[0]), []byte(args[1]), []byte(args[2]), []byte(args[3]), []byte(eventID)}}
	respone, err0 := t.Client.Execute(req)
	if err0 != nil {
		return []byte{0x00}, err0
	}

	err1 := eventResult(notifier, eventID)
	if err1 != nil {
		return []byte{0x00}, err1
	}

	return respone.Payload, nil
}
func (t *ServiceSetup) AuditPatient(args []string) ([]byte, error) {
	if len(args) != 4 {
		return []byte{0x00}, fmt.Errorf("给定的参数个数不符合要求！")
	}
	eventID := "eventAuditPatient"
	reg, notifier := regitserEvent(t.Client, t.ChaincodeID, eventID)
	defer t.Client.UnregisterChaincodeEvent(reg)
	req := channel.Request{ChaincodeID: t.ChaincodeID, Fcn: "auditForPatient", Args: [][]byte{[]byte(args[0]), []byte(args[1]), []byte(args[2]), []byte(args[3]), []byte(eventID)}}
	respone, err0 := t.Client.Execute(req)
	if err0 != nil {
		return []byte{0x00}, err0
	}

	err1 := eventResult(notifier, eventID)
	if err1 != nil {
		return []byte{0x00}, err1
	}

	return respone.Payload, nil
}
